<template>
	<view>
		<view class="example">
			<uni-forms ref="valiForm" :rules="rules" :modelValue="formData">
				<uni-forms-item label="姓名" required name="userName">
					<uni-easyinput v-model="formData.userName" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="工号" required name="userId">
					<uni-easyinput v-model="formData.userId" placeholder="请输入工号" />
				</uni-forms-item>
				<uni-forms-item label="申请人电话" required name="userPhone">
					<uni-easyinput v-model="formData.userPhone" placeholder="请输入电话" />
				</uni-forms-item>
				<uni-forms-item label="车牌号" required name="autoPlateNum">
					<uni-data-select v-model="formData.autoPlateNum" :localdata="formData.autoPlateNumRange"
						placeholder="请选择车牌号"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="维修类型" required name="autoRepairType">
					<uni-data-select v-model="formData.autoRepairType" :localdata="autoRepairTypeRange"
						placeholder="请选择维修类型"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="故障描述" required name="repairDescribe">
					<uni-easyinput type="textarea" v-model="formData.repairDescribe" placeholder="请输入故障描述" />
				</uni-forms-item>
				<uni-forms-item label="维修厂" required name="repairFactory">
					<uni-easyinput v-model="formData.repairFactory" placeholder="请输入维修厂" />
				</uni-forms-item>
				<uni-forms-item label="送修日期" required name="repairStartTime">
					<uni-datetime-picker type="datetime" return-type="string" v-model="formData.repairStartTime" />
				</uni-forms-item>
				<uni-forms-item label="期望取车日期" required name="repairEndTime">
					<uni-datetime-picker type="datetime" return-type="string" v-model="formData.repairEndTime" />
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="dialogToggle('info')">提交</button>
		</view>
	</view>
	<uni-popup ref="alertDialog" type="dialog">
		<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="提醒" content="此操作将提交维修申请,是否继续？"
			@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
	</uni-popup>
</template>

<script>
	export default {
		name: "repairForm",
		data() {
			return {
				formData: {
					userName: "",
					userId: "",
					userPhone: "",
					autoPlateNum: "",
					autoRepairType: "",
					repairDescribe: "",
					repairFactory: "",
					repairStartTime: "",
					repairEndTime: "",
					submitTime: "",
					autoPlateNumRange: [],
					repairOrderStatus: "流转中",
					repairOrderProgress: "1"
				},
				SubmitTodo: {
					userId: "",
					todoTime: "",
					todoType: "",
					orderId: "",
					todoStatus: ""
				},
				ref: "valiForm",
				DepartmentAdminId: null,
				NextUserRole: "部门管理员",
				AutoOrderId: null,
				SubmitCode: [],

				autoRepairTypeRange: [{
					value: "汽车大修",
					text: "汽车大修"
				}, {
					value: "汽车总成大修",
					text: "汽车总成大修"
				}, {
					value: "汽车小修",
					text: "汽车小修"
				}, {
					value: "零部件修理",
					text: "零部件修理"
				}],
				rules: {
					userName: {
						rules: [{
							required: true,
							errorMessage: "姓名不能为空",
						}, ],
					},
					userId: {
						rules: [{
							required: true,
							errorMessage: "工号不能为空",
						}, ],
					},
					userPhone: {
						rules: [{
							required: true,
							errorMessage: "申请人电话不能为空",
						}, ],
					},
					autoPlateNum: {
						rules: [{
							required: true,
							errorMessage: "车牌号不能为空",
						}, ],
					},
					autoRepairType: {
						rules: [{
							required: true,
							errorMessage: "维修类型不能为空",
						}, ],
					},
					repairDescribe: {
						rules: [{
							required: true,
							errorMessage: "故障描述不能为空",
						}, ],
					},
					repairFactory: {
						rules: [{
							required: true,
							errorMessage: "维修厂不能为空",
						}, ],
					},
					repairStartTime: {
						rules: [{
							required: true,
							errorMessage: "送修日期不能为空",
						}, ],
					},
					repairEndTime: {
						rules: [{
							required: true,
							errorMessage: "期望取车日期不能为空",
						}, ],
					},
				},
			};
		},
		methods: {
			UpdateCurrentTime() {
				const currentDateTime = new Date();

				const year = currentDateTime.getFullYear();
				const month = String(currentDateTime.getMonth() + 1).padStart(2, '0');
				const day = String(currentDateTime.getDate()).padStart(2, '0');

				const hours = String(currentDateTime.getHours()).padStart(2, '0');
				const minutes = String(currentDateTime.getMinutes()).padStart(2, '0');
				const seconds = String(currentDateTime.getSeconds()).padStart(2, '0');

				this.formData.submitTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

				console.log('Updated submit_time:', this.formData.submitTime);
			},
			fetchAutoPlateNums() {
				uni.request({
					url: 'http://localhost:8088/fetchPlateNums', // 后端接口地址
					method: 'GET',
				}).then((response) => {
					console.log('Response from server:', response);

					// 根据实际后端返回的数据结构进行处理
					const responseData = response.data;

					if (responseData && responseData.data && Array.isArray(responseData.data)) {
						const autoPlateNumRange = responseData.data.map((item) => ({
							value: item.autoPlateNum,
							text: item.autoPlateNum,
						}));

						// 更新formData中的autoPlateNumRange
						this.formData.autoPlateNumRange = autoPlateNumRange;
					} else {
						console.error('Invalid response format. Expected an array.');
					}
				}).catch((error) => {
					console.error('Failed to fetch autoPlateNums:', error);
				});
			},
			addRepairOrder() {
				return new Promise((resolve, reject) => {
					this.$refs[this.ref].validate()
						.then(() => {
							console.log('Form submission successful');
							console.log('Submitted data:', this.formData);

							// Update current time
							this.UpdateCurrentTime();

							// Send data to the backend
							uni.request({
								url: 'http://localhost:8088/addRepairOrder',
								method: 'POST',
								data: this.formData,
								success: (res) => {
									console.log('Backend response:', res.data);
									uni.showToast({
										title: '提交成功'
									});
									resolve(res
										.data); // Indicate successful asynchronous operation
								},
								fail: (err) => {
									console.error('Error submitting data:', err);
									uni.showToast({
										title: '提交失败，请稍后重试',
										icon: 'none'
									});
									reject(err); // Handle asynchronous error
								},
							});
						})
						.catch((err) => {
							console.log('Form validation failed');
							console.log('Validation errors:', err);

							// Print specific error information for each field
							Object.keys(err).forEach((field) => {
								console.log(`Error in ${field}: ${err[field]}`);
							});

							uni.showToast({
								title: '表单校验失败，请检查输入',
								icon: 'none'
							});
							reject(err); // Handle validation error
						});
				});
			},
			GetGeneralUserId() {
				console.log("testGetGeneralUserId");
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://localhost:8088/getGeneralUserId',
						method: 'GET',
						success: (res) => {
							const temp = res.data.data;
							console.log(temp);

							if (temp) {
								const result = Object.values(temp);
								this.GeneralAdminId = result[0];
								resolve();
							} else {
								// Handle the case when temp is undefined or null
								reject(new Error('Data is undefined or null'));
							}
						},

						fail: (err) => {
							console.log(err);
							reject(err); // 处理异步错误
						}
					});
				});
			},

			GetRepairOrderId() {
				console.log('执行 GetRepairOrderId');
				return new Promise((resolve, reject) => {
					// 确保 this.FormData 被正确初始化
					if (!this.formData) {
						console.error('this.FormData 未正确初始化');
						reject(new Error('FormData is not initialized'));
						return;
					}

					uni.request({
						url: 'http://localhost:8088/getRepairOrderId', // 替换为你的 API 端点
						method: 'GET', // 根据需要调整 HTTP 方法（GET、POST 等）
						data: {
							submitTime: this.formData.submitTime
						},
						success: (res) => {
							const temp = res.data.data;
							const result = Object.values(temp);
							this.RepairOrderId = result[0];
							console.log(this.RepairOrderId);
							resolve(); // 表示异步操作成功
						},
						fail: (err) => {
							console.error(err);
							reject(err); // 处理异步错误
						},
					});
				});
			},

			AddTodo() {
				return new Promise((resolve, reject) => {
					console.log('Executing AddTodo');
					console.log('DepartmentAdminId:', this.GeneralAdminId);
					console.log('RepairOrderId:', this.RepairOrderId);
					if (!this.GeneralAdminId || !this.RepairOrderId) {
						console.error('DepartmentAdminId or RepairOrderId is not set.');
						reject('DepartmentAdminId or RepairOrderId is not set.');
						return;
					}

					console.log('DepartmentAdminId:', this.GeneralAdminId);
					this.SubmitTodo.userId = this.GeneralAdminId;
					this.SubmitTodo.todoTime = this.formData.submitTime; // 修正拼写错误
					this.SubmitTodo.todoType = "维修申请综合办审批";
					this.SubmitTodo.orderId = this.RepairOrderId;
					this.SubmitTodo.todoStatus = "未完成";
					console.log(this.SubmitTodo.userId);

					uni.request({
						url: 'http://localhost:8088/insertTodo',
						method: 'POST',
						data: this.SubmitTodo,
						success: (res) => {
							console.log('Backend response:', res.data);

							this.SubmitCode.push(res.data.code);
							if (res.data.code === '0') {
								console.log(res.data.code);
								resolve();
							} else {
								console.log(res.data.msg);
								reject(res.data.msg);
							}
						},
						fail: (err) => {
							console.log(err);
							reject(err);
						},
					});
				});
			},
			handleButtonClick() {
				// Button click event handler
				this.addRepairOrder()
					.then(() => {
						// Proceed to the next method only if addAutoOrder is successful
						return this.GetGeneralUserId();
					})
					.then(() => {
						// Proceed to the next method only if queryDepartmentUserId is successful
						return this.GetRepairOrderId();
					})
					.then(() => {
						// Proceed to the next method only if GetAutoOrderId is successful
						return this.AddTodo();
					})
					.then(() => {
						// All four methods executed successfully
						console.log('All methods executed successfully');
					})
					.catch((error) => {
						// Handle errors from any of the methods
						console.error('Error:', error);
					});
			},
			dialogToggle(type) {
				this.msgType = type
				this.$refs.alertDialog.open()
			},
			dialogConfirm() {
				console.log('点击确认')
				this.handleButtonClick();
			},
			dialogClose() {
				console.log('点击取消')
			},
		},

		created() {
			this.fetchAutoPlateNums();
		},
	}
</script>

<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>